<template>
 <div class="card-table">
    <div class="header">
        <div @click="$router.go(-1)" class="goBackIcon">
            <i class="el-icon-arrow-left" style="margin-right:1px;"></i>返回
        </div>
        <div style="margin-left:16px;">{{this.typeOrder !== 'edit' ? '新增' : '编辑'}}一焙工单</div>
    </div>
    <div class="main">
      <el-form size="small" :inline="true" :rules="rules" ref="formBurn" :model="form" label-width="100px">
        <el-form-item style="margin-left:-30px" label="炉室号" prop="deviceType">
            <el-select :disabled="typeOrder !== 'add'" style="width:300px;" v-model="form.stoveNumber" placeholder="请选择设备类型">
                <el-option v-for="(item, index) in ovenTypes" :key="index" :label="item.stoveNumber + '号'" :value="item.stoveNumber"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item style="margin-left:24px;" label="开始生产时间">
          <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" :disabled="typeOrder !== 'add'" placeholder="选择生产时间" v-model="form.inStoveTime" type="datetime" style="width: 300px;"></el-date-picker>
          <!-- <div class="dateClass">
            <el-form-item prop="dateDay">
              <el-date-picker type="date" placeholder="选择日期" v-model="form.dateDay" style="width: 70%;"></el-date-picker>
            </el-form-item>
            <div class="line">-</div>
            <el-form-item prop="dateTime">
              <el-time-picker placeholder="选择时间" v-model="form.dateTime" style="width: 70%;"></el-time-picker>
            </el-form-item>
          </div> -->
        </el-form-item>
        <hr style="height:1px;border:none;border-top:1px solid rgb(228, 236, 240);"/>
        <div class="mainTable" style="margin:12px;">
          <el-table
              :cell-style="{ padding: '8px' }"
              :header-cell-style="getRowClass"
              :data="form.box"
              style="width: 80%">
              <el-table-column
                  width="150"
                  align="center"
                  prop="prop"
                  label="炉号 - 箱号 - (上/下)" >
                  <template slot-scope="{ row }">
                      {{form.stoveNumber + ' - ' + row.boxNumber + ' - ' + row.layer}}
                  </template>
              </el-table-column>
              <el-table-column
                  header-align="center"
                  align="center"
                  label="装炉产品" >
                  <el-table-column align="center" width="">
                      <template slot-scope="" slot="header">
                        <span style="font-weight:100;">产品内容</span>
                      </template>
                      <template slot-scope="{row}">
                      <span>{{row.inputProducts}}</span>
                      </template>
                  </el-table-column>
                  <el-table-column
                      align="center"
                      width="170">
                      <template slot-scope="" slot="header">
                          <span style="font-weight:100;">操作</span>
                      </template>
                      <template slot-scope="scope">
                          <el-form-item style="margin:0;">
                              <el-button v-if="typeOrder !== 'add'" :disabled="scope.row.inputProducts === '' || scope.row.layerStatus === '已出炉'" @click="outOven(scope.row,scope.$index)" icon="el-icon-shopping-cart-full" type="primary">出炉</el-button>
                              <el-button v-else @click="chooseProduct(scope.row)" icon="el-icon-edit-outline" plain type="primary">选择产品</el-button>
                          </el-form-item>
                      </template>
                  </el-table-column>
              </el-table-column>
              <el-table-column
                  align="center"
                  prop="prop"
                  v-if="typeOrder !== 'add'"
                  label="生产结束时间"
                  width="250">
                  <!-- <template slot-scope="{ $index,row }">
                    <el-form-item v-if="row.inputProducts !== ''" style="margin:0;" :prop="`box[${$index}].outStoveTime`">
                      <el-date-picker
                        style="width:200px"
                        v-model="row.outStoveTime"
                        type="datetime"
                        placeholder="选择出炉时间"
                        value-format="yyyy-MM-dd HH:mm:ss">
                      </el-date-picker>
                    </el-form-item>
                  </template> -->
                  <template slot-scope="{ row }">{{row.outStoveTime}}</template>
              </el-table-column>
              <el-table-column
                  align="center"
                  prop="prop"
                  v-if="typeOrder !== 'add'"
                  label="出炉人"
                  width="width">
                  <template slot-scope="{ row }">{{row.checkOvenMan}}</template>
                  <!-- <template slot-scope="{$index,row}">
                    <el-form-item v-if="row.inputProducts !== ''" style="margin:0;" :prop="`box[${$index}].checkOvenMan`">
                      <el-input v-model="row.checkOvenMan"></el-input>
                    </el-form-item>
                  </template> -->
              </el-table-column>
              <el-table-column
                  align="center"
                  label="状态">
                  <template slot-scope="{$index,row}">
                    <el-form-item  style="margin:0;" :prop="`box[${$index}].layerStatus`">
                      <el-tag size="medium" :type="row.layerStatus === '已出炉' ? 'success' : 'warning'">{{row.layerStatus}}</el-tag>
                    </el-form-item>
                  </template>
              </el-table-column>
          </el-table>
        </div>
        <div class="footer">
            <div style="display:inline-block;width:80px;"></div>
            <el-button @click="submitForm('formBurn')" type="primary">提交</el-button>
            <el-button @click="$router.go(-1), cancels('formBurn')">取消</el-button>
        </div>
        <!-- <div
          class="groups"
          v-for="item in form.box"
          :key="item.id">
            <el-form-item :label="form.stoveNumber + ' - ' + item.boxNumber + ' - ' + item.layer">
              <el-input disabled style="width: 40%" type="textarea" :autosize="{ minRows: 1, maxRows: 2}" v-model="item.inputProducts"></el-input>
              <el-button :disabled="typeOrder !== 'add'" style="margin-left: 25px" type="primary" icon="el-icon-plus" @click="chooseProduct(item)">选择产品</el-button>
              <el-button v-if="typeOrder !== 'add' && item.inputProducts !== ''" style="margin-left: 25px" icon="el-icon-shopping-cart-full" type="primary" plain @click="outOven(item)">出炉</el-button>
              <div v-if="typeOrder !== 'add' && item.outingTimeOven" class="timeline">
                <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择出炉时间" v-model="item.outStoveTime" type="datetime" style="width: 100%;"></el-date-picker>
              </div>
            </el-form-item>
        </div> -->
      </el-form>
      <el-dialog
        :modal-append-to-body="false"
        title="选择产品"
        :visible.sync="dialogTable"
        width="50%">
        <el-table
          ref="multipleTable"
          :data="tableData"
          tooltip-effect="dark"
          style="width: 100%; height: 430px"
          class="tableClass"
          @row-click="rowClick"
          @selection-change="handleSelectionChange">
          <el-table-column
            type="selection"
            align="center"
            width="65">
          </el-table-column>
          <el-table-column
            prop="rodNumber"
            align="center"
            label="产品编号">
          </el-table-column>
          <el-table-column
            prop="productType"
            label="产品类型"
            align="center">
          </el-table-column>
          <el-table-column
            prop="diameterSpecification"
            label="直径规格"
            align="center">
          </el-table-column>
          <el-table-column
            prop="specification"
            label="规格型号"
            align="center">
          </el-table-column>
        </el-table>
        <!-- 还有分页 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancelTable()">取 消</el-button>
          <el-button type="primary" @click="setSelection()">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog
        :modal-append-to-body="false"
        :title="outOvenDialog"
        :visible.sync="dialogoutOvenTable"
        width="30%">
        <el-form size="medium" :model="formOven" ref="formOven" :rules="formOvenRules" label-width="120px" class="demo-form">
          <el-form-item style="margin:20px 10px;" label="生产结束时间" prop="outStoveTime">
              <el-date-picker
                style="width:350px;"
                v-model="formOven.outStoveTime"
                type="datetime"
                placeholder="选择日期时间"
                value-format="yyyy-MM-dd HH:mm:ss">
              </el-date-picker>
          </el-form-item>
          <el-form-item style="margin:20px 10px;" label="出炉人" prop="checkOvenMan">
              <el-input  style="width:350px;" v-model="formOven.checkOvenMan"></el-input>
          </el-form-item>
          <div class="footer">
              <div style="display:inline-block;width:300px;"></div>
              <el-button @click="makeSure('formOven')" type="primary">确定</el-button>
              <el-button @click="cancelSure('formOven')">取消</el-button>
          </div>
        </el-form>
      </el-dialog>
    </div>
 </div>
</template>

<script>
import { getProductData, getStoveNumData, addBurnOrderCreate, firstRoastingUpdate } from '@/api/stoveApi/stoveWorker.js'
import { mapGetters } from 'vuex'
// import { nomalPages } from '@/mixin'

export default {
  name: 'firstBurnAdd',
  components: {},
  // mixins: [nomalPages],
  data () {
    return {
      form: {
        stoveNumber: '1',
        box: [
          {
            id: '1',
            boxNumber: '1',
            layer: '上',
            products: [],
            inputProducts: '',
            outingTimeOven: false,
            layerStatus: '待出炉',
            checkOvenMan: '',
            outStoveTime: '' // 出炉时间
          },
          {
            id: '2',
            boxNumber: '1',
            layer: '下',
            products: [],
            inputProducts: '',
            layerStatus: '待出炉',
            outingTimeOven: false,
            outStoveTime: '' // 出炉时间
          },
          {
            id: '3',
            boxNumber: '2',
            layer: '上',
            inputProducts: '',
            products: [],
            layerStatus: '待出炉',
            outingTimeOven: false,
            outStoveTime: '' // 出炉时间
          },
          {
            id: '4',
            boxNumber: '2',
            layer: '下',
            inputProducts: '',
            products: [],
            layerStatus: '待出炉',
            outingTimeOven: false,
            outStoveTime: '' // 出炉时间
          },
          {
            id: '5',
            boxNumber: '3',
            layer: '上',
            inputProducts: '',
            products: [],
            layerStatus: '待出炉',
            outingTimeOven: false,
            outStoveTime: '' // 出炉时间
          },
          {
            id: '6',
            boxNumber: '3',
            layer: '下',
            inputProducts: '',
            products: [],
            layerStatus: '待出炉',
            outingTimeOven: false,
            outStoveTime: '' // 出炉时间
          },
          {
            id: '7',
            boxNumber: '4',
            layer: '上',
            inputProducts: '',
            products: [],
            layerStatus: '待出炉',
            outingTimeOven: false,
            outStoveTime: '' // 出炉时间
          },
          {
            id: '8',
            boxNumber: '4',
            layer: '下',
            inputProducts: '',
            products: [],
            layerStatus: '待出炉',
            outingTimeOven: false,
            outStoveTime: '' // 出炉时间
          },
          {
            id: '9',
            boxNumber: '5',
            layer: '上',
            inputProducts: '',
            products: [],
            layerStatus: '待出炉',
            outingTimeOven: false,
            outStoveTime: '' // 出炉时间
          },
          {
            id: '10',
            boxNumber: '5',
            layer: '下',
            inputProducts: '',
            products: [],
            layerStatus: '待出炉',
            outingTimeOven: false,
            outStoveTime: '' // 出炉时间
          }
        ],
        inStoveTime: '',
        writeMan: ''
      },
      formOven: {}, // 出炉填的俩
      selectType: true, // 是否选择设备类型
      deviceTypeSuppliers: [],
      dialogTable: false,
      ovenTypes: [
        {
          label: '1号',
          value: '1'
        },
        {
          label: '2号',
          value: '2'
        },
        {
          label: '3号',
          value: '3'
        },
        {
          label: '4号',
          value: '4'
        },
        {
          label: '5号',
          value: '5'
        },
        {
          label: '6号',
          value: '6'
        },
        {
          label: '7号',
          value: '7'
        },
        {
          label: '8号',
          value: '8'
        },
        {
          label: '9号',
          value: '9'
        },
        {
          label: '10号',
          value: '10'
        },
        {
          label: '11号',
          value: '11'
        },
        {
          label: '12号',
          value: '12'
        },
        {
          label: '13号',
          value: '13'
        },
        {
          label: '14号',
          value: '14'
        },
        {
          label: '15号',
          value: '15'
        },
        {
          label: '16号',
          value: '16'
        },
        {
          label: '17号',
          value: '17'
        },
        {
          label: '18号',
          value: '18'
        },
        {
          label: '19号',
          value: '19'
        },
        {
          label: '20号',
          value: '20'
        }
      ],
      rules: {
        stoveNumber: [
          { required: true, message: '请选择炉室号码', trigger: 'change' }
        ],
        dateDay: [
          { required: true, message: '请填写日期', trigger: 'blur' }
        ],
        dateTime: [
          { required: true, message: '请填写时间', trigger: 'blur' }
        ]

      },
      formOvenRules: {
        checkOvenMan: [
          { required: true, message: '请填写出炉人', trigger: 'blur' }
        ],
        outStoveTime: [
          { required: true, message: '请填写出炉时间', trigger: 'blur' }
        ]
      },
      tableData: [],
      multipleSelection: [],
      outOvenDialog: '',
      dialogoutOvenTable: false,
      middleVariable: null // 作为选好table和input之间
    }
  },
  computed: {
    ...mapGetters({
      getUserInfos: 'getUserInfo'
    })
  },
  watch: {
  },
  created () {
    this.typeOrder = this.$route.query.type
    if (this.typeOrder === 'edit') {
      this.form = JSON.parse(this.$route.query.formCopy)
      this.form.box.forEach(item => {
        item.inputProducts = ''
        item.products.forEach(i => {
          item.inputProducts = item.inputProducts + i.rodNumber + ', '
        })
        item.inputProducts = item.inputProducts.substring(0, item.inputProducts.length - 2)
      })
    }
    this.getStoveNum()
    // this.setAddChosenProduct([])
  },
  mounted () {
  },
  methods: {
    getStoveNum () {
      getStoveNumData().then(res => {
        this.ovenTypes = res.data.data
      })
    },
    getRidOfOtherChoose (boxItem) {
      var allboxCopy = JSON.parse(JSON.stringify(this.$refs.formBurn.model.box.filter(item => {
        return item.id !== boxItem.id
      })))
      var othersOf = []
      allboxCopy.forEach(i => {
        othersOf.push.apply(othersOf, i.products)
      })
      // console.log('别的input框已经选中的othersOf', othersOf)
      return othersOf
    },
    chooseProduct (boxItem) {
      // console.log('boxItem', boxItem)
      this.middleVariable = boxItem
      var otherChosen = this.getRidOfOtherChoose(boxItem)
      // console.log('otherChosen', otherChosen)
      this.dialogTable = true
      getProductData().then(res => {
        // console.log('待装炉产品', res.data.data)
        const dataCopy = JSON.parse(JSON.stringify(res.data.data))
        this.tableData = this.filterChecked(otherChosen, dataCopy)
        this.toggleSelection(this.middleVariable.products)
      })
    },
    toggleSelection (rows) {
      if (rows) {
        this.$nextTick(() => {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(this.tableData.find(item => { return row.rodNumber === item.rodNumber }), true) // 切换某一行的选中状态
          })
        })
      }
      // this.$nextTick(() => { // 如果加分页
      //   for (let i = 0; i < rows.length; i++) {
      //     for (let j = 0; j < this.tableData.length; j++) {
      //       if (rows[i].id === this.tableData[j].id) {
      //         this.$refs.multipleTable.toggleRowSelection(this.tableData[j], true)
      //       }
      //     }
      //   }
      // })
      // else {
      //   this.$refs.multipleTable.clearSelection()
      // }
    },
    filterChecked (ischecked, all) {
      var willCheck = all.filter(i => {
        return !ischecked.some(el => el.rodNumber === i.rodNumber)
      })
      return willCheck
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
      // console.log('选中的row multipleSelection', this.multipleSelection)
    },
    rowClick (row, column, event) {
      this.$nextTick(() => {
        this.$refs.multipleTable.toggleRowSelection(this.tableData.find(item => { return row.rodNumber === item.rodNumber }), true) // 切换某一行的选中状态
      })
    },
    setSelection () {
      this.middleVariable.products = this.multipleSelection
      var strs = ''
      this.multipleSelection.forEach(item => {
        strs = strs + item.rodNumber + ' , '
      })
      this.middleVariable.inputProducts = strs.substring(0, strs.length - 2)
      this.dialogTable = false
    },
    cancelTable () {
      this.multipleSelection = []
      this.$refs.multipleTable.clearSelection()
      this.dialogTable = false
    },
    cancelSure (formName) {
      this.dialogoutOvenTable = false
      this[formName] = this.$options.data.call(this)[formName]
    },
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.typeOrder === 'add') {
            this.form.writeMan = this.getUserInfos.account
            console.log('创建一烧', this.form)
            addBurnOrderCreate(this.form).then(res => {
              if (res.data.code === 200) {
                this.$message({
                  type: 'success',
                  message: '创建成功'
                })
                this.dialogTable = false
                this.$router.go(-1)
                this.$refs.formBurn.resetFields()
              } else {
                this.$message({
                  type: 'warning',
                  message: res.data.message
                })
              }
            })
          } else {
            this.form.createTime = this.form.completeCreateTime
            console.log('出炉了', this.form)
            firstRoastingUpdate(this.form).then(res => {
              if (res.data.code === 200) {
                this.$message({
                  type: 'success',
                  message: '出炉成功'
                })
                this.$router.go(-1)
              } else {
                this.$message({
                  type: 'warning',
                  message: res.data.message
                })
              }
            })
          }
        } else {
          this.$message({
            type: 'warning',
            message: '提交失败'
          })
          return false
        }
      })
    },
    cancels (formName) {
      this.$refs[formName].resetFields()
    },
    // 出炉
    outOven (item, index) {
      this.outOvenDialog = `${item.boxNumber + ' - ' + item.layer + ' '}出炉`
      this.dialogoutOvenTable = true
      console.log('item', item, index)
      this.formOven = { outStoveTime: item.outStoveTime, checkOvenMan: item.checkOvenMan, nums: index }
      // console.log('this.formOven', this.formOven)
    },
    makeSure (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.form.box[this.formOven.nums].checkOvenMan = this.formOven.checkOvenMan
          this.form.box[this.formOven.nums].outStoveTime = this.formOven.outStoveTime
          this.dialogoutOvenTable = false
          this.$message({
            type: 'success',
            message: '填写成功'
          })
        } else {
          this.$message({
            type: 'warning',
            message: '请将信息填写完整'
          })
          return false
        }
      })
    }
  }
}
</script>

